//
//  PicturePickerViewController.swift
//  weibo19
//
//  Created by Arvin on 15/11/19.
//  Copyright © 2015年 Arvin. All rights reserved.
//

import UIKit
import SnapKit

private let reuseIdentifier = "PicturePickerCell"
private let column: CGFloat = 4
private let pictureItemMargin: CGFloat = 10

class PicturePickerViewController: UICollectionViewController {
    
    // 图片容器
    var pictures = [UIImage]()
    
    init() {
        let layout = UICollectionViewFlowLayout()
        layout.minimumInteritemSpacing = pictureItemMargin
        layout.minimumLineSpacing = pictureItemMargin
        let w = (screenWidth - ((column + 1) * CGFloat(pictureItemMargin))) / 4.00001
            layout.itemSize = CGSizeMake(w , w)
        layout.sectionInset = UIEdgeInsetsMake(pictureItemMargin, pictureItemMargin, pictureItemMargin, pictureItemMargin)
        super.init(collectionViewLayout: layout)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        collectionView?.backgroundColor = UIColor.whiteColor()
        // Register cell classes
        self.collectionView!.registerClass(PicturePickerCell.self, forCellWithReuseIdentifier: reuseIdentifier)
    }
    
    // MARK: UICollectionViewDataSource
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictures.count + 1
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! PicturePickerCell
        cell.pictureCellDelegate = self
        if indexPath.item <= pictures.count - 1 {
            cell.picture = pictures[indexPath.item]
        } else {
            cell.picture = nil
        }
        return cell
    }
    
    
}

extension PicturePickerViewController: PicturePickerCellDelegate {
    func didAddPicture(pictureCell: PicturePickerCell) {

        // 创建系统的图片选择器
        let pickerImage = UIImagePickerController()
        // 设置代理
        pickerImage.delegate = self
        // 允许编辑, 设置头像
        // pickerImage.allowsEditing = true
        presentViewController(pickerImage, animated: true, completion: nil)
    }
    
    func didDeletePiture(pictureCell: PicturePickerCell) {
        let indexPath = collectionView?.indexPathForCell(pictureCell)
        
        let index = Int(indexPath!.item)
        if index == pictures.count {
            return
        }
        
        if pictures.count != 0   {
            pictures.removeAtIndex((indexPath?.item)!)
            collectionView?.reloadData()
        }
    }
    
}

extension PicturePickerViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        pictures.append(image)
        collectionView?.reloadData()
        
        // 一旦实现协议方法, dimiss就交给程序员
        dismissViewControllerAnimated(true, completion: nil)
    }
    
}

@objc protocol PicturePickerCellDelegate: NSObjectProtocol {
    optional func didAddPicture(pictureCell: PicturePickerCell)
    optional func didDeletePiture(pictureCell: PicturePickerCell)
}

class PicturePickerCell: UICollectionViewCell {
    
    // MARK: 代理
    var pictureCellDelegate: PicturePickerCellDelegate?
    
    // MARK: 点击事件
    @objc private func addPicture() {
        // 判空, 点击的是否是已经添加的图片
        if picture != nil {
            return
        }
        pictureCellDelegate?.didAddPicture?(self)
    }
    
    @objc private func deletPicture() {
        
        pictureCellDelegate?.didDeletePiture?(self)
    }
    
    // MARK: 赋值给属性
    var picture: UIImage? {
        didSet {
            deleteView.hidden = (picture == nil)
            if picture == nil {
                // 在这了, 没有对picture的引用, picture为nil
                addView.image = UIImage(named: "tabbar_compose_icon_add")
            } else {
                // 这里cell对picture引用, picture不为nil
                addView.image = picture
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor.grayColor()
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        
        contentView.addSubview(addView)
        contentView.addSubview(deleteView)
        addView.userInteractionEnabled = true
        deleteView.userInteractionEnabled = true
        let addTap = UITapGestureRecognizer(target: self, action: "addPicture")
        let deletTap = UITapGestureRecognizer(target: self, action: "deletPicture")
        addView.addGestureRecognizer(addTap)
        deleteView.addGestureRecognizer(deletTap)
        
        addView.snp_makeConstraints { (make) -> Void in
            make.top.left.right.bottom.equalTo(contentView)
        }
        deleteView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(contentView)
            make.centerX.equalTo(contentView.snp_right).offset(-10)
        }
        
        contentView.snp_makeConstraints { (make) -> Void in
            make.left.top.right.bottom.equalTo(self)
        }
        
    }

    private lazy var addView: UIImageView = UIImageView(image: UIImage(named: "tabbar_compose_icon_add"))

    private lazy var deleteView: UIImageView = UIImageView(image: UIImage(named: "compose_photo_close"))
    
}


